package com.xxmw.transaction.interceptor;

import com.xxmw.transaction.common.annotation.UserLoginIgnore;
import com.xxmw.transaction.common.entity.R;
import com.xxmw.transaction.common.utils.Assert;
import com.xxmw.transaction.common.utils.JWTUtil;
import com.xxmw.transaction.model.app.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

	public static final String STAFF_KEY = "user";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String method = request.getMethod();
		if ("options".equalsIgnoreCase(method) ){
			return true;
		}
		// 不用登录的路径验证
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		UserLoginIgnore loginIgnore = handlerMethod.getMethodAnnotation(UserLoginIgnore.class);
		if (Assert.isNotNullOrEmpty(loginIgnore)) {
			// 有相应注解的方法跳过校验，不需要登录
			return true;
		}

		String token = request.getHeader("appToken");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		if (StringUtils.isBlank(token)) {
			response.setContentType("text/plain;charset=UTF-8");
			response.getWriter().print(R.error(600, "登录信息失效，请重新登录").toJSONString());
			return false;
		}

		try{
			User user = JWTUtil.getUser(token);
			request.setAttribute(STAFF_KEY, user);
		}catch (Exception e) {
			response.getWriter().print(R.error(600, "登录信息失效，请重新登录"));
			return false;
		}
		return true;
	}

}
